package me.yricky.alia.ui.fileListPage

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import me.yricky.alia.ui.StateViewModel
import java.io.File

/**
 * @author Yricky
 * @date 2022/1/27
 */
class FileListViewModel {
    private val coroutineScope:CoroutineScope = CoroutineScope(Dispatchers.Main)
    data class ViewState(
        val currDir:MutableStateFlow<File> = MutableStateFlow(File(".")),
        val filter:MutableStateFlow<String> = MutableStateFlow(""),
        val files:MutableStateFlow<List<String>> = MutableStateFlow(emptyList()),
        /**
         * Map< extra name uppercase without dot , (Path of file)->Unit >
         */
        val openMethod:MutableStateFlow<Map<String,(String)->Unit>> = MutableStateFlow(emptyMap())
    )
    val viewState = ViewState()

    fun setFilter(f:String){
        viewState.filter.value = f
        updateList()
    }

    fun setPath(path:String){
        val f = File(path)
        if(f.canRead() && f.isDirectory){
            viewState.currDir.value = File(path)
            setFilter("")
        }
    }

    fun setOpenMethods(openMethod:Map<String,(String)->Unit>){
        viewState.openMethod.value = openMethod
    }

    private fun updateList(){
        coroutineScope.launch {
            viewState.files.value = withContext(Dispatchers.IO){
                viewState.currDir.value.listFiles()?.sorted()?.map { it.absolutePath }?.let{
                    listOf("${viewState.currDir.value.path}/..").plus(it)
                } ?: emptyList()
            }
        }
    }

}